package com.tf_cut.admin.backend.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.backend.vo.RegisterVo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.user.service.UserService;
import com.tf_cut.admin.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/backend/person/mobile")
@Slf4j
public class PersonMobileController {

    @Autowired
    private BackEndApi backEndApi;

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserAuthorityService sysUserAuthorityService;

    @Autowired
    private SysAuthorityService sysAuthorityService;

    @Autowired
    private AgentMobileController agentMobileController;

    @Value("${applets.open}")
    private Boolean appletsOpen;


    @PostMapping("/register")
    public  Result register(@RequestBody RegisterVo registerVo){

        try {
            //判断手机号重复
            Result<SysUserVo> byLoginName = this.sysUserService.findByLoginName(registerVo.getLoginName());
            if(byLoginName.getData()==null||!byLoginName.isFlag()){
                return   Result.of(registerVo,false,"用户名重复");
            }
            String code = CacheUtil.get(registerVo.getLoginName());
            String verifyCode = registerVo.getVerifyCode();
            CacheUtil.delete(registerVo.getLoginName());
            log.debug("code:"+code);
            log.debug("VerifyCode:"+verifyCode);
            //20201117 小程序注册验证二维码; //20201207 默认0000不验证
            if(!verifyCode.trim().equals("0000")) {
                if (StringUtils.isBlank(verifyCode) || StringUtils.isBlank(code) || StringUtils.compareIgnoreCase(verifyCode, code) != 0) {
                    return Result.of(null, false, "验证码错误");
                }
            }
            //新增系统用户
            SysUserVo sysUserVo = SysUserVo.builder()
                    .createTime(new Date())
                    .updateTime(new Date())
                    .lastChangePwdTime(new Date())
                    .loginName(registerVo.getLoginName())
                    .userName(registerVo.getCompanyName())
                    .password(registerVo.getPassword())
                    .valid("Y")
                    .limitMultiLogin("Y")
                    .build();
            Result<SysUserVo> save = this.sysUserService.save(sysUserVo);
            //增加用户权限
            List<SysAuthorityVo> seller_user = this.sysAuthorityService.list(SysAuthorityVo.builder().authorityName("PERSON_USER").build()).getData();
            if(seller_user==null||seller_user.isEmpty()){
                return   Result.of(registerVo,false,"数据错误");
            }

            SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(save.getData().getUserId())
                    .authorityId(seller_user.get(0).getAuthorityId()).createTime(new Date()).build();

            this.sysUserAuthorityService.save(build);

            //增加个人信息
            JSONObject object=new JSONObject();
            object.put("loginId",save.getData().getUserId());
            object.put("loginName",registerVo.getLoginName());
            object.put("cardStatus","N");//没有认证
            String result = this.backEndApi.insertPersonAndAccount(object.toJSONString());
            JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);

            if(!jsonObject.getBoolean("flag")){
                return Result.of(null, false, "系统错误,创建失败");
            }

            //增加登录信息

            JSONObject login=new JSONObject();
            login.put("isverifycode", false);
            login.put("username",registerVo.getLoginName());
            login.put("password", registerVo.getPassword());

            Object login1 = this.agentMobileController.login(login.toJSONString());
            save.setMsg(login1+"");

            return save;

        } catch (Exception e) {
            e.printStackTrace();
            return   Result.of(registerVo,false,"登录名重复");
        }



    }

    @GetMapping("/appletsOpen")
    public Boolean appletsOpen(){

        String apPlETS_open = this.backEndApi.getdataDicVoWithCode("APPlETS_OPEN");
        if(StringUtils.isNotEmpty(apPlETS_open)){
            List<JSONObject> objects = JSONObject.parseArray(apPlETS_open,JSONObject.class);
            if(objects.size()>0){
                JSONObject jsonObject = objects.get(0);
                String datadicValue = jsonObject.getString("datadicValue");
                if(StringUtils.isNotEmpty(datadicValue)&&datadicValue.equals("1")){
                    return true;
                }
            }
        }
        return  false;
    }

    @GetMapping(value = "/getPersonByloginId")
    public String get(@RequestParam("loginId")  String loginId){
        return backEndApi.personmobileget(loginId);
    }

    @PostMapping(value = "/personAuth")
    public String updateInfo(@RequestBody String svo){
        //增加个人授权标志
        JSONObject jsonObject = JSONObject.parseObject(svo);
        jsonObject.put("isPersonAuth", 1);
        return backEndApi.updatepersonmobileInfo(jsonObject.toJSONString());
    }

    @PostMapping(value = "/billinsert")
    public String insertBill(@RequestBody String svo){
        return backEndApi.insertPersonBill(svo);
    }

    @PostMapping(value = "/save/bank")
    public String insertPersonBank(@RequestBody String svo){
        return backEndApi.insertPersonBank(svo);
    }

    @GetMapping(value = "/bank")
    public String getPersonBank(@RequestParam("personId")  String personId){
        return backEndApi.getPersonBank(personId);
    }

}
